#include "CCLuaEngine.h"
#include "tolua++.h"
#include "tolua_fix.h"
#include "LuaCCTableView.h"

MyCCTableView* MyCCTableView::create(CCScrollViewDirection direct, CCSize size, CCArray *items){
  MyCCTableView *table = new MyCCTableView(items);
  table->initWithViewSize(size, NULL);
  table->autorelease();
  table->setDataSource(table);
  table->setDirection(direct);
  table->setDelegate(table);
  table->_updateContentSize();

  if(direct==kCCScrollViewDirectionHorizontal){
    table->setBarSpriteByName("scrollerbarH.png");
  }else if(direct==kCCScrollViewDirectionVertical){
    table->setBarSpriteByName("scrollerbarV.png");
  }


  //table->setBounceable(false);
  //table->setClippingToBounds(false);  
  //table->setContentSize(size);
  
  //table->ignoreAnchorPointForPosition(false); 
  //table->setAnchorPoint(CCPointMake(0, 0));
  //CCPoint p = table->getAnchorPoint();
  //CCSize s = table->getContentSize();
  //CCLog("MyCCTableView::create %f, %f, %f, %f, %d", p.x, p.y, s.width, s.height, table->isIgnoreAnchorPointForPosition()); 
  //table->reloadData();
  return table;
}

MyCCTableView::MyCCTableView(CCArray *items){
  //spriteName_ = "yellowlight.png";
  barSprite_ = NULL;
  isTimer = false;
  oldX_ = -1;
  oldY_ = -1;
  items_ = NULL;
  cells_ = NULL;
  setItems(items);
}

MyCCTableView::~MyCCTableView(){
  for(int i=0; i<items_->count(); i++){
    items_->objectAtIndex(i)->release();
    cells_->objectAtIndex(i)->release();
  }
  items_->release();
  //cells_->release();
  /*if(barSprite_ && barSprite_->getParent()){
    barSprite_->getParent()->removeChild(barSprite_, true);
    barSprite_ = NULL;
  }*/
}

void MyCCTableView::setItems(CCArray *items){
  if(items_){
    items_->release();
  }
  if(cells_){
    cells_->release();
  }
  items_ = items;
  items_->retain();
  cells_ = CCArray::create();
  cells_->retain();
  for(int i=0; i<items_->count(); i++){
    CCTableViewCell *cell = new CCTableViewCell();
    CCNode* node= (CCNode*)items_->objectAtIndex(i);
    node->setTag(1111);
    node->setAnchorPoint(CCPointZero);
    cell->addChild(node);
    cells_->addObject(cell);
  }
  if(items_->count()>0){
    CCNode* node = (CCNode*)items_->objectAtIndex(0);
    itemSize_ = node->getContentSize();
  }else{
    itemSize_ = CCSizeMake(0,0);
  }
}
void MyCCTableView::setDatas(CCArray *items){
  setItems(items); 
  reloadData();
}
CCTableViewCell* MyCCTableView::tableCellAtIndex(CCTableView *table, unsigned int idx){
  return (CCTableViewCell*)cells_->objectAtIndex(idx);
  //CCTableViewCell *cell = table->dequeueCell();
  //if (!cell) {
    CCTableViewCell *cell = new CCTableViewCell();
    cell->autorelease();
    CCNode* node= (CCNode*)items_->objectAtIndex(idx);
    node->setAnchorPoint(CCPointZero);
    //CCLog("MyCCTableView::tableCellAtIndex %d", idx);
    /*
    CCSize size = getContentSize(); 
    CCScrollViewDirection direction = getDirection();
    if(direction == kCCScrollViewDirectionHorizontal){
      node->setPosition();
    }else if(direction == kCCScrollViewDirectionVertical){
      node->setPosition();
    }*/
    cell->addChild(node);
  //}else{
  //}
  return cell;
}

unsigned int MyCCTableView::numberOfCellsInTableView(CCTableView *table){
  int count = items_->count();
  //CCLog("MyCCTableView::numberOfCellsInTableView %d", count);
  return count;
}

CCSize MyCCTableView::cellSizeForTable(CCTableView *table){
  //CCNode* node = (CCNode*)items_->objectAtIndex(0);
  //CCSize size = node->getContentSize();
  //CCLog("MyCCTableView::cellSizeForTable %f %f", size.width, size.height);
  //return size;
  return itemSize_;
}
void MyCCTableView::setBarSpriteByName(const char* name){
  spriteName_ = name;
}
void MyCCTableView::setBarSprite(const char* spriteName){
  //barSprite_=CCSprite::create(spriteName);
  //barSprite_->retain();
  //printf("%p %p\n", this, this->getContainer());
}
void MyCCTableView::onTimer(float t){
  printf("MyCCTableView::onTimer\n");
  CCPoint offset = this->getContentOffset();
  if(int(offset.x)==oldX_ && int(offset.y)==oldY_){
    printf("MyCCTableView::onTimer unscheduleSelector %p\n", barSprite_);
    CCDirector::sharedDirector()->getScheduler()->unscheduleSelector(schedule_selector(MyCCTableView::onTimer), this);
    isTimer = false; 
    oldX_ = -1;
    oldY_ = -1;
    barSprite_->runAction(CCSequence::create(CCDelayTime::create(0.2), CCFadeOut::create(0.5), 
                            CCCallFuncN::create(this, callfuncN_selector(MyCCTableView::onMoveEnd)), NULL));
  }
  oldX_ = int(offset.x);
  oldY_ = int(offset.y);
}
void MyCCTableView::onMoveEnd(CCNode* sender){
  //sender->setVisible(false);
  sender->getParent()->removeChild(sender, false);
  barSprite_ = NULL;
  printf("MyCCTableView::onMoveEnd %p\n", barSprite_);
}

void MyCCTableView::scrollViewDidScroll(CCScrollView* view) {
  CCTableView::scrollViewDidScroll(view);   
  if(spriteName_.empty()){
    return;
  }
  /*if(this->getParent()==NULL){
    return;
  }*/
  if(barSprite_==NULL){
    printf("MyCCTableView::scrollViewDidScroll create bar\n");
    barSprite_ = CCSprite::create(spriteName_.c_str());
  }
  if(barSprite_->getParent()==NULL){
    //printf("MyCCTableView::scrollViewDidScroll addchild %p\n", this->getParent());
    //this->getParent()->addChild(barSprite_);
    CCNode::addChild(barSprite_, 1, -1);
  }
  //printf("MyCCTableView::scrollViewDidScroll set bar visible\n");
  //barSprite_->setVisible(true); 
  CCRect rect = barSprite_->getTextureRect();
  CCSize size = this->getViewSize();
  CCSize size1 = this->getContainer()->getContentSize();
  CCPoint offset = this->getContentOffset();
  //printf("@@ %f %f %f %f %f %f %f %f\n", rect.size.width, rect.size.height, size.width, size.height, size1.width, size1.height, offset.x, offset.y);

  //kCCScrollViewDirectionHorizontal = 0,
  //kCCScrollViewDirectionVertical,

  if(this->getDirection()==kCCScrollViewDirectionHorizontal){
    int begin = rect.size.width/2;
    int end = size.width-rect.size.width/2;
    int total = size.width - rect.size.width;
    int delta = -offset.x; 
    float r = delta/(size1.width-size.width);
    float pos = total*r + begin;
    if(pos>end){pos = end;}
    if(pos<begin){pos = begin;}
    //CCPoint p = this->getPosition();
    CCPoint tp = ccp(pos, rect.size.height/2);
    //printf("@@ %f %f %f %f\n",r,  pos, tp.x, tp.y);
    barSprite_->setPosition(tp);
    //printf("%p %p %p\n", this, this->getContainer(), barSprite_->getParent());
    //barSprite_->setPosition(ccp(p.x+pos+rect.size.height/2, p.y));
  }else if(this->getDirection()==kCCScrollViewDirectionVertical){
    int begin = rect.size.height/2;
    int end = size.height-rect.size.height/2;
    int total = size.height - rect.size.height;
    int delta = -offset.y; 
    float r = delta/(size1.height-size.height);
    float pos = total*r + begin;
    if(pos>end){pos = end;}
    if(pos<begin){pos = begin;}
    //printf("@@ %f %f\n",r,  pos);
    //CCPoint p = this->getPosition();
    CCPoint tp = ccp(size.width-rect.size.width/2, pos);
    barSprite_->setPosition(tp);
    //barSprite_->setPosition(ccp(p.x+size.width-rect.size.width/2, p.y+pos));
  }
  if(!isTimer){
    printf("MyCCTableView::onTimer scheduleSelector\n");
    isTimer = true;
    CCDirector::sharedDirector()->getScheduler()->scheduleSelector(schedule_selector(MyCCTableView::onTimer), this, 1, false);
  }
}


int tolua_Cocos2d_CCTableView_create(lua_State* tolua_S){
  int direction = ((int)  tolua_tonumber(tolua_S,2,0));
  CCSize size = *((CCSize*)  tolua_tousertype(tolua_S,3,0));
  CCArray* items= ((CCArray*)  tolua_tousertype(tolua_S,4,0));
  
  
  //CCLog("c_Cocos2d_CCTableView_create begin %f %f", size.width, size.height);
  MyCCTableView *tv = MyCCTableView::create((CCScrollViewDirection)direction, size, items);
  //CCLog("c_Cocos2d_CCTableView_create end %f %f %p", size.width, size.height, tv);
  //tv->setBarSprite("yellowlight.png");
  //tv->getBarSprite()->setPosition(tv->getPosition());
  MyCCTableView* tolua_ret = tv;
  int nID = (tolua_ret) ? (int)tolua_ret->m_uID : -1;
  int* pLuaID = (tolua_ret) ? &tolua_ret->m_nLuaID : NULL;
  toluafix_pushusertype_ccobject(tolua_S, nID, pLuaID, (void*)tolua_ret,"CCTableView");    
  //CCLog("c_Cocos2d_CCTableView_create return %f %f", size.width, size.height);
  return 1;
}
int tolua_Cocos2d_CCTableView_setDatas(lua_State* tolua_S){
  MyCCTableView* self = (MyCCTableView*)  tolua_tousertype(tolua_S,1,0);
  CCArray* items= ((CCArray*)  tolua_tousertype(tolua_S,2,0));
  self->setDatas(items);
  return 1;
}
int tolua_Cocos2d_CCTableView_setBarSpriteByName(lua_State* tolua_S){
  MyCCTableView* self = (MyCCTableView*)  tolua_tousertype(tolua_S,1,0);
  const char* name = ((const char*)  tolua_tostring(tolua_S,2,0));
  self->setBarSpriteByName(name);
  return 1;
}
int tolua_Cocos2d_CCTableView_cellAtIndex(lua_State* tolua_S){
  MyCCTableView* self = (MyCCTableView*)  tolua_tousertype(tolua_S,1,0);
  int index = ((int)  tolua_tonumber(tolua_S,2,0));

  //CCLog("tolua_Cocos2d_CCTableView_cellAtIndex %p, %d %p", self, index, self->cellAtIndex(index+1));
  CCNode* tolua_ret = self->cellAtIndex(index+1)->getChildByTag(1111);
  int nID = (tolua_ret) ? (int)tolua_ret->m_uID : -1;
  int* pLuaID = (tolua_ret) ? &tolua_ret->m_nLuaID : NULL;
  toluafix_pushusertype_ccobject(tolua_S, nID, pLuaID, (void*)tolua_ret,"CCNode");
  return 1;
}
int tolua_Cocos2d_CCTableView_getItemSize(lua_State* tolua_S){
  MyCCTableView* self = (MyCCTableView*)  tolua_tousertype(tolua_S,1,0);
  CCSize tolua_ret = (CCSize)  self->getItemSize();  
  void* tolua_obj = tolua_copy(tolua_S,(void*)&tolua_ret,sizeof(CCSize));
  tolua_pushusertype(tolua_S,tolua_obj,"CCSize");
  tolua_register_gc(tolua_S,lua_gettop(tolua_S));
  return 1;
}
